﻿<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web.Script.Serialization" %>

<script runat="server">

  protected void Page_Load(object sender, EventArgs e)
  {
    //給預選清單和紅配綠使用
    string b2c_code = Request["B2C_CODE"];
    string smas_code = Request["SMAS_CODE"];
    string qty = Request["qty"];
    string catid = Request["catid"];
    string type = Request["Type"];
    AddProductToCart(b2c_code, smas_code, qty, catid, type);
    //Response.Redirect("~/Shopping/ShoppingCart.aspx");
  }

  /// <summary>
  /// 加入購物車
  /// </summary>
  /// <param name="b2c_code">商品編號</param>
  /// <param name="smas_code">規格編號</param>
  /// <param name="qty">訂購數量</param>
  /// <param name="catid">館別類型 0:一般、1:哩上加禮、2:紅配綠、3:限時折扣、4:期間限定</param>
  /// <param name="product_type">1:現金、若是紅配綠館別, 種類：4:紅標、5:綠標</param>
  /// <returns></returns>
  [System.Web.Services.WebMethod]
  public static string AddProductToCart(string b2c_code, string smas_code, string qty, string catid, string product_type = "1")
  {
    string results = "-1";
    string CURR_QTY = GetStorageQtyBySmasCode(smas_code) ;
    if (CURR_QTY == "0" || int.Parse(qty) > int.Parse(CURR_QTY))
    { 
      return "-2";  //當庫存量不足時，回傳代號讓jQuery處理
    }
    
    int quantity;
    if (!String.IsNullOrEmpty(b2c_code) &&
      !String.IsNullOrEmpty(smas_code) &&
      int.TryParse(qty, out quantity))
    {
      //目前B2C_MALL_HOME.B2C_MALL_GetProductDetail回傳的產品資料規格不完整
      //B2C_MALL_HOME ws = new B2C_MALL_HOME();
      //string jsonString = 
      //  ws.B2C_MALL_GetProductDetail("aaaa", HttpContext.Current.User.Identity.Name, b2c_code);
      //JObject restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);

      JObject restoredObject;
      string jsonString;
      //0:一般
      //1:哩上加禮
      //2:紅配綠
      //3:限時折扣
      //4:期間限定
      switch (catid)
      {
        case "0":
          B2C_MALL_GetProductList_0 ws0 = new B2C_MALL_GetProductList_0();
          ws0.Url = ConfigurationManager.AppSettings["B2C_MALL_GetProductList_0"].ToString();
          jsonString = ws0.B2C_MALL_GetProductDetail(CommonUtil.GetWebDevice(), HttpContext.Current.User.Identity.Name, b2c_code);
          restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
          break;
        case "1":
          B2C_MALL_GetProductList_1 ws1 = new B2C_MALL_GetProductList_1();
          ws1.Url = ConfigurationManager.AppSettings["B2C_MALL_GetProductList_1"].ToString();
          jsonString = ws1.B2C_MALL_GetProductDetail(CommonUtil.GetWebDevice(), HttpContext.Current.User.Identity.Name, b2c_code);
          restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
          break;
        case "2":
          B2C_MALL_HOME ws2 = new B2C_MALL_HOME();
          ws2.Url = ConfigurationManager.AppSettings["B2C_MALL_HOME"].ToString();
          jsonString = ws2.B2C_MALL_GetProductDetail(CommonUtil.GetWebDevice(), HttpContext.Current.User.Identity.Name, b2c_code);
          restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
          break;
        case "3":
          B2C_MALL_GetProductList_3 ws3 = new B2C_MALL_GetProductList_3();
          ws3.Url = ConfigurationManager.AppSettings["B2C_MALL_GetProductList_3"].ToString();
          jsonString = ws3.B2C_MALL_GetProductDetail(CommonUtil.GetWebDevice(), HttpContext.Current.User.Identity.Name, b2c_code);
          restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
          break;
        case "4":
          B2C_MALL_GetProductList_4 ws4 = new B2C_MALL_GetProductList_4();
          ws4.Url = ConfigurationManager.AppSettings["B2C_MALL_GetProductList_4"].ToString();
          jsonString = ws4.B2C_MALL_GetProductDetail(CommonUtil.GetWebDevice(), HttpContext.Current.User.Identity.Name, b2c_code);
          restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
          break;
        default:
          B2C_MALL_HOME ws5 = new B2C_MALL_HOME();
          ws5.Url = ConfigurationManager.AppSettings["B2C_MALL_HOME"].ToString();
          jsonString = ws5.B2C_MALL_GetProductDetail(CommonUtil.GetWebDevice(), HttpContext.Current.User.Identity.Name, b2c_code);
          restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
          break;
      }
      if (restoredObject != null)
      {
        JArray jArray = (JArray)restoredObject["Prd_Type_Ary"];
        dynamic dynObj = jArray.Where(p => p["SMAS_CODE"].ToString() == smas_code).SingleOrDefault();
        string Prod_Cat_ID = "1";
        //價錢：規則簡單化，就是商品會提供特價或會員獨享價兩種價錢(會員獨享價不一定會有)，
        //只要結帳前沒有登入會員，那就一定是特價
        //如果有登入會員，該物品沒有設定會員獨享價(不是所有東西都會設定)，那就是特價
        //如果物品有設定會員獨享價，那就一定要提供會員獨享價。會員獨享價一定會比特價便宜
        int ProductPrice = int.Parse(restoredObject["Prd_PRICE_Ary"][0]["ACT_PRICE"].ToString());
        //int ProductPrice = (int)(catid == "2"
        //  ? decimal.Parse(restoredObject["Prd_PRICE_Ary"][0]["RedGreenPrice"].ToString())
        //  : decimal.Parse(restoredObject["Prd_PRICE_Ary"][0]["ACT_PRICE"].ToString()));

        //紅配綠識別
        //string RorG = catid == "2" ? restoredObject["R_OR_G"].ToString() : "";        

        //哩上加哩的價錢
        //string Mileage = catid == "1" ? restoredObject["Prd_PRICE_Ary"][0]["MILEAGE"].ToString() : "";
        string Mileage = "";
        int MileageCash = 0;
        //if (catid == "1")
        //{
        //  int.TryParse(restoredObject["Prd_PRICE_Ary"][0]["CASH"].ToString(), out MileageCash);
        //  if (product_type == "2" || product_type == "3")  //使用里程抵扣時
        //  {
        //    ProductPrice = MileageCash;
        //  }
        //}       

        //購物車中優惠資訊呈現，抓取Prod_Cat_ID        
        string promotion = "";
        dynamic b2ccodeary = restoredObject["B2C_CODE_ary"];
        string CurrentCatID = b2ccodeary[0].Prod_Cat_ID;
        if (!string.IsNullOrEmpty(CurrentCatID))
        {
          CurrentCatID = CurrentCatID.Replace("(", "").Replace(")", "").Replace("X", "");
          string[] CatArray = CurrentCatID.Split(',');
          if (CatArray.Length > 0)
          {
            Prod_Cat_ID = CatArray[CatArray.Length - 1].ToString();
          }
        }

        if (!string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
        {
          if (catid == "0" || catid == "3" || catid == "4")
          {
            if (!string.IsNullOrEmpty(restoredObject["Prd_PRICE_Ary"][0]["MbrPrice"].ToString())
              && restoredObject["Prd_PRICE_Ary"][0]["MbrPrice"].ToString() != "0")
            {
              //會員登入且有會員獨享價(不為0)
              //ProductPrice = int.Parse(restoredObject["Prd_PRICE_Ary"][0]["MbrPrice"].ToString());
            }
          }
        }

        if (catid == "1")//哩上加哩
        {
          if (!string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name)
            && (product_type == "2" || product_type == "3"))  //使用里程抵扣時
          {
            if (HttpContext.Current.Request.Cookies["LoginInfo"] != null)
            {
              HttpCookie LoginInfo = HttpContext.Current.Request.Cookies["LoginInfo"] as HttpCookie;
              string strAuthType = LoginInfo.Values["AuthType"].ToString();
              string MemberType = LoginInfo.Values["MemberType"].ToString();
              if (strAuthType == "1") //正式會員時
              {
                var Prd_PRICE = restoredObject["Prd_PRICE_Ary"]
                .Where(p => p["FFP_CARD_TYPE"].ToString() == MemberType)
                .SingleOrDefault();
                if (Prd_PRICE != null)
                {
                  int.TryParse(Prd_PRICE["CASH"].ToString(), out MileageCash);
                  ProductPrice = MileageCash;
                  Mileage = Prd_PRICE["MILEAGE"].ToString();
                }
              }
            }
          }
          else //哩上加哩若無使用里程抵扣時，則為視為一般商品
          {
            Prod_Cat_ID = "999";
          }
        }


        if (catid == "3")//限時折扣(整點特賣)
        {
          string START_DATE = b2ccodeary[0].START_DATE_range.ToString("d");
          string START_DATE_Time = b2ccodeary[0].START_DATE_range.ToString("t");
          string END_DATE_Time = b2ccodeary[0].END_DATE_range.ToString("t");
          promotion = "<p class=\"red-text\"><strong>優惠期間 "
            + START_DATE + "<br/>"
            + START_DATE_Time
            + " - "
            + END_DATE_Time
            + "</strong><br/>活動結束將調回原價</p>";
          Prod_Cat_ID = "8";
        }
        else if (catid == "4")//期間限定
        {
          string START_DATE = b2ccodeary[0].START_DATE.ToString("d");
          string END_DATE = b2ccodeary[0].END_DATE.ToString("d");
          promotion = "<p class=\"red-text\"><strong>優惠期間 "
            + START_DATE
            + " - "
            + END_DATE
            + "</strong><br/>活動結束將調回原價</p>";
          Prod_Cat_ID = "8";
        }
        else if (catid == "2")//紅配綠
        {
          Prod_Cat_ID = "8";
        }

        CartItem cartItem = new CartItem()
        {
          ItemId = Guid.NewGuid().ToString(),
          SMAS_CODE = smas_code,
          B2C_CODE = b2c_code,
          ImagePath = restoredObject["IMAGE_PATH_M_Ary"][0]["IMAGE_PATH_M"].ToString(),
          ProductName = restoredObject["B2C_CODE_ary"][0]["B2C_CODE_NAME"].ToString(),
          Price = ProductPrice,
          Quantity = quantity,
          Spec = dynObj.Prd_Type,
          Status = (string.IsNullOrEmpty(dynObj.Storage_Qty.ToString()) || dynObj.Storage_Qty == "0") ? "補貨中" : "正常",
          ProdCatID = restoredObject["B2C_CODE_ary"][0]["Output_Prod_Cat_ID"].ToString(),
          Prod_Cat_ID = Prod_Cat_ID,
          LastUpdated = DateTime.Now,
          Mileage = Mileage,
          Cash = MileageCash,
          Type = product_type,
          StorageQty = dynObj.Storage_Qty,
          Promotion = promotion,
          Prod_Status = "0",
          Prod_Memo = ""
        };

        ShoppingCart userShoppingCart;
        if (HttpContext.Current.Session["ShoppingCart"] == null)
        {
          userShoppingCart = new ShoppingCart();
          userShoppingCart.Created = DateTime.Now;
          userShoppingCart.AddToCart(cartItem);
          userShoppingCart.LastUpdated = DateTime.Now;
          HttpContext.Current.Session["ShoppingCart"] = userShoppingCart;
        }
        else
        {
          userShoppingCart = HttpContext.Current.Session["ShoppingCart"] as ShoppingCart;
          userShoppingCart.AddToCart(cartItem);
          userShoppingCart.LastUpdated = DateTime.Now;
        }

        var cartItems = userShoppingCart.CartItems.OrderBy(c => c.LastUpdated).ToList();
        results = JsonConvert.SerializeObject(cartItems);
      }
      return results;
    }
    else
    {
      throw new Exception("ERROR : 載入 AddToCart.aspx 時未傳入必要參數SMAS_CODE以及數量.");
    }
  }

  /// <summary>
  /// 取得購物車
  /// </summary>
  /// <returns></returns>
  [System.Web.Services.WebMethod]
  public static string GetCartItems()
  {
    string results = "-1";
    if (HttpContext.Current.Session["ShoppingCart"] != null)
    {
      ShoppingCart userShoppingCart = HttpContext.Current.Session["ShoppingCart"] as ShoppingCart;
      var cartItems = userShoppingCart.CartItems.OrderBy(c => c.LastUpdated).ToList();
      results = JsonConvert.SerializeObject(cartItems);
    }
    return results;
  }

  /// <summary>
  /// 刪除購物車中的項目
  /// </summary>
  /// <param name="smas_code">指定欲刪除的SMAS_CODE</param>
  /// <returns></returns>
  [System.Web.Services.WebMethod]
  public static string DeleteCartItems(string smas_code)
  {
    string results = "-1";
    if (HttpContext.Current.Session["ShoppingCart"] != null)
    {
      ShoppingCart userShoppingCart = HttpContext.Current.Session["ShoppingCart"] as ShoppingCart;
      userShoppingCart.RemoveItem(smas_code);
      var cartItems = userShoppingCart.CartItems.OrderBy(c => c.LastUpdated).ToList();
      results = JsonConvert.SerializeObject(cartItems);
    }
    return results;
  }

  /// <summary>
  /// 由smas_code取得庫存量
  /// </summary>
  /// <param name="smas_code">商品smas_code</param>
  /// <returns>庫存量</returns>
  [System.Web.Services.WebMethod]
  public static string GetStorageQtyBySmasCode(string smas_code)
  {
    string CURR_QTY = "0";
    try
    { 
      B2C_MALL_HOME ws = new B2C_MALL_HOME();
      ws.Url = ConfigurationManager.AppSettings["B2C_MALL_HOME"].ToString();
      string jsonString = ws.B2C_MALL_GetQuantity(CommonUtil.GetWebDevice(),
        HttpContext.Current.User.Identity.Name,
        smas_code);
      JObject restoredObject = JsonConvert.DeserializeObject<JObject>(jsonString);
      string Is_Valid = restoredObject["Is_Valid"].ToString();
      string msg = restoredObject["Msg"].ToString();
      if (Is_Valid == "Y")
      {
        CURR_QTY = restoredObject["CURR_QTY"].ToString();
        if (string.IsNullOrEmpty(CURR_QTY))        
        {
          CURR_QTY = "0";
        }
      }      
    }
    catch (Exception)
    {
      return "0";
    }
    return CURR_QTY;
  }    
</script>


